import { jsonParse } from 'service/util/index.js'
import config from 'service/config'
import ajax from 'service/ajax'

export default {
    state: {
        // 借款次数
        borrowCount: null,
        // 身份证号
        idCard: null,
        // 头像url
        headImg: null,
        // 借款状态
        borrowStatus: null,
        // 可用额度
        useLimit: null,
        // 用户状态 0:无,1:身份认证完成,3:基本信息认证完成,4-审核中,5:已审核,7:补件中,9:驳回
        status: null,
        // 用户卡号
        userId: null,
        // 用户姓名
        realName: null,
        // 授信状态
        creditStatus: null,
        // 认证中心提交按钮状态
        buttonStatus: null,
        // 手机号
        mobile: null,
        // 未读消息总数
        msgUnreadCount: null,
        // 定时器
        refreshTimer: null
    },
    getters: {
        // 是否登录
        userLogined: state => {
            return state.userId != null
        },
        // 借款状态
        userBorrowStatus: state => {
            return state.borrowStatus
        },
        // 用户状态
        userStatus: state => {
            return state.status
        },
        // 认证等级，即认证项目数
        userCreditNums: state => {
            var nums = 0
            if (state.creditStatus) {
                var caIndexs = [0, 1, 3, 4]
                for (var index in caIndexs) {
                    if (state.creditStatus[caIndexs[index]] == '1') {
                        nums++
                    }
                }
            }
            return nums
        },
        // 身份认证状态 true-已认证
        userCardIdStatus: state => {
            var status = state.creditStatus ? state.creditStatus.slice(0, 1) : 0
            return status == 1
        },
        // 个人信息认证状态 true-已认证
        userPersonalStatus: state => {
            var status = state.creditStatus ? state.creditStatus.slice(1, 2) : 0
            return status == 1
        },
        // 银行卡认证状态 true-已认证
        userBankcardStatus: state => {
            var status = state.creditStatus ? state.creditStatus.slice(2, 3) : 0
            return status == 1
        },
        // 运营商认证状态 true-已认证
        userOperatorStatus: state => {
            var status = state.creditStatus ? state.creditStatus.slice(3, 4) : 0
            return status == 1
        },
        // 芝麻信用认证
        userSesameStatus: state => {
            var status = state.creditStatus ? state.creditStatus.slice(4, 5) : 0
            return status == 1
        }
    },
    mutations: {
        // 用户状态更新
        userUpdate(state, payload) {
            for (var k in state) {
                if (payload[k] !== undefined) {
                    state[k] = payload[k]
                }
            }
        },
        // 清除用户信息
        userClear(state) {
            for (var k in state) {
                state[k] = null
            }
        }
    },
    actions: {
        // 用户信息保存到 localstorage 中
        userSaveToStorage({ state }) {
            window.localStorage.setItem('user', JSON.stringify(state))
        },
        // 从 localstorage 中读取用户信息
        userGetFromStorage({ commit, state }) {
            var userStorage = window.localStorage.getItem('user')
            if (userStorage) {
                var payload = jsonParse(userStorage)
                commit('userUpdate', payload)
            }
        },
        // 用户状态更新
        userUpdate({ commit, dispatch }, payload) {
            commit('userUpdate', payload)
            dispatch('userSaveToStorage')
        },
        // 清除用户信息
        userClear({ commit, dispatch }, payload) {
            window.localStorage.removeItem('user')
            commit('userClear')
        },
        // 调用 /user/info 接口更新信息
        userInfoAjax({ state, dispatch }, payload) {
            return ajax.user.info({
                userId: state.userId
            }).then(res => {
                var { code, data } = res.data
                if (code == 'S') {
                    dispatch('userUpdate', data)
                }
                return res
            })
        },
        // 审核中状态的时候，两分钟刷新一次页面
        userRefreshAjax({ state, dispatch, getters }, payload) {
            if (payload && payload.close) {
                clearInterval(state.refreshTimer)
            } else {
                // 定时2分钟查询用户信息
                clearInterval(state.refreshTimer)
                state.refreshTimer = setInterval(() => {
                    if (getters.userLogined) {
                        ajax.user.info({
                            userId: state.userId
                        }).then(res => {
                            var { code, data } = res.data
                            if (code == 'S') {
                                dispatch('userUpdate', data)
                                // 如果用户的订单状态不是审核中并且用户状态不是审核中，结束轮询
                                if (data.borrowStatus != 'C' && data.status != '4') {
                                    clearInterval(state.refreshTimer)
                                }
                            }
                        })
                    }
                }, 1000 * 60 * 3)
            }
        },
        // 白骑士指纹设备上传
        userConfitAjax({ state, dispatch, getters }, payload) {
            if (!getters.userLogined) {
                return
            }
            $ajax.user.config({
                userId: state.userId
            }).then(res => {
                var { isTokenKey, tokenKey } = res.data.data
                if (isTokenKey == 'Y') {
                    window._saber = {
                        partnerId: config.partnerId,
                        tokenKey: tokenKey,
                        callback: dfCallBack
                    }
                    var aa = document.createElement('script')
                    aa.async = true
                    aa.src = (document.location.protocol == 'https:' ? 'https://' : 'http://') + 'df.baiqishi.com/static/webdf/saber.js?t=' + (new Date().getTime() / 3600000).toFixed(0)
                    var bb = document.getElementsByTagName('script')[0]
                    bb.parentNode.insertBefore(aa, bb)
                }
                function dfCallBack() {
                    $ajax.user.saveTokenKey({
                        userId: state.userId,
                        tokenKey: tokenKey
                    })
                }
            })
        }
    }
}